<template>
  <div class="x-bar" :id="chartId" :option="option"></div>
</template>

<script>
import { formatNum } from "../util/tool";
export default {
  props: {
    chartId: {
      type: String
    },
    options: {
      type: Object
    }
  },
  data() {
    return {
      chart: "",
      option: {
        color: [
          "#ff48f0",
          "#fff838",
          "#3052ff",
          "#ff8a18",
          "#6fff36",
          "#00e6ff"
        ],
        tooltip: {
          trigger: "item",
          formatter: "{b}<br />{c}人 ({d}%)"
        },
        legend: {
          icon: 'circle',
          itemWidth: 10,
          textStyle: {
            color: "#dedede",
            fontSize: 12
          },
          padding: 8,
          data: this.options.legend
        },
        series: [
          {
            type: "pie",
            radius: "50%",
            center: ["50%", "60%"],
            itemStyle: {
              emphasis: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)"
              }
            },
            label: {
              normal: {
                formatter: "{b|{b}} \n{hr|}\n {c|{c}}",
                backgroundColor: "rgba(0,0,0,0.1)",
                borderColor: "rgba(0,198,255,0.4)",
                borderWidth: 1,
                borderRadius: 5,
                padding: [8, 15],
                rich: {
                  b: {
                    color: "#49d9fe",
                    fontSize: 14
                  },
                  hr: {
                    width: '100%',
                    height: '4',
                    backgroundColor: 'transparent'
                  },
                  c: {
                    color: '#fff000',
                    fontSize: 12,
                    align: 'center'
                  }
                }
              }
            },
            data: this.options.sData,
          }
        ]
      }
    };
  },
  watch: {
    options: {
      handler(newVal, oldVal) {
        if (this.chart) {
          if (newVal) {
            this.option.legend.data = newVal.legend;
            this.option.series[0].data = newVal.sData;
            this.chart.setOption(this.option);
          } else {
            this.chart.setOption(this.option);
          }
        } else {
          this.init();
        }
      },
      deep: true
    }
  },
  methods: {
    init() {
      this.chart = this.$echarts.init(document.getElementById(this.chartId));
      this.chart.setOption(this.option);
      window.addEventListener("resize", this.chart.resize);
    }
  },
  mounted() {
    this.init();
  }
};
</script>

<style lang="stylus" scoped>
.x-bar {
  width: 100%;
  height: 85%;
}
</style>
